import Joi from 'joi'
import { Result } from '~~/lib/helper/result'
import prisma from '~~/lib/prisma'

export default defineEventHandler(async (event) => {
  const userId = getLoginId(event)
  const body = await readBody(event)
  const schema = Joi.object({
    notebookId: Joi.number().required(),
    title: Joi.string().required(),
    contentMd: Joi.string().required(),
    state: Joi.string().required(),
  })

  try {
    await schema.validateAsync(body)
  } catch (error: any) {
    return Result.Error('参数错误！' + error.message)
  }
  try {
    // 创建文章
    const note = await prisma.note.create({
      data: {
        title: body.title,
        contentMd: body.contentMd,
        state: body.state,
        uid: userId,
      },
    })
    // 关联文章与文集
    await prisma.notebookNote.create({
      data: {
        noteId: note.id,
        notebookId: body.notebookId,
      },
    })
  } catch (error) {
    console.log('error', error)
    return Result.Error('创建文章失败！')
  }
  return Result.Ok(null, 200, '创建文章成功！')
})
